package com.sghd.football.utils.http;

import com.sghd.common.utils.json.JsonUtils;
import com.sghd.football.module.game.service.model.ReturnMsg;
import com.sghd.football.utils.encrypt.EncryptUtil;
import com.sghd.football.utils.encrypt.PropUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

public class HttpUtil {
	/**
	 * 发送数据
	 *
	 * @param jsonData
	 *            表单数据
	 * @param sendType
	 *            post or get
	 * @param encrptType
	 *            加密 or 不加密
	 * @throws Exception
	 */
	public static ReturnMsg sendData(Map<String, Object> jsonData, int sendType, int encrptType, String servletName) throws Exception {
		ReturnMsg rmsg = new ReturnMsg();
		Map<String, Object> paramJson = new HashMap<>();

		paramJson.put("encrptType", encrptType);

		if (encrptType == HttpConfig.encrypt_java)
			paramJson.putAll(EncryptUtil.encryptData(jsonData));
		else
			paramJson.putAll(jsonData);

		if (sendType == HttpConfig.send_post)
			rmsg = post(paramJson, HttpConfig.from_shunjin_yes, servletName);

		return rmsg;
	}

	@SuppressWarnings("deprecation")
	public static RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).setConnectionRequestTimeout(6000)
			.setStaleConnectionCheckEnabled(true).build();

	public static ReturnMsg post(Map<String, Object> json, String shunjin, String servletName) {
		ReturnMsg rmsg = new ReturnMsg();
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		// 创建httppost
		HttpPost httppost = new HttpPost(PropUtil.getProperty("third.service.url") + "/" + servletName);
		httppost.setHeader("Connection", "close");
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<>();
		createFormParams(json, formparams);

		UrlEncodedFormEntity uefEntity;
		CloseableHttpResponse response = null;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			httppost.setHeader("shunjin", shunjin);
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String returnStr = EntityUtils.toString(entity, "UTF-8");
				rmsg = JsonUtils.string2Object(returnStr, ReturnMsg.class);
			}
		}  catch (IOException e) {
			e.printStackTrace();
		} finally {
			httppost.releaseConnection();
			// 关闭连接,释放资源
			try {
				if(response != null){
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return rmsg;
	}

	private static void createFormParams(Map<String, Object> json, List<NameValuePair> formparams) {
		Iterator<Entry<String, Object>> iter = json.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, Object> entry = iter.next();
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
		}
	}
	//
}
